﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows.Data;
using System.IO;
using System.Linq;

using Cinch;
using MEFedMVVM.ViewModelLocator;
using MEFedMVVM.Services.Contracts;
using MEFedMVVM.Common;
using System.Windows.Threading;
using System.Configuration;


namespace Anata.Client
{
    /// <summary>
    /// </summary>
    public class KonsumenSelectViewModel : ViewModelBase
    {
        #region Data
        #region Data.Primitives
        private String filterKeyword = "";

        private bool isAllLoaded = false;
        private int pageLoaded = 0;
        private DispatcherTimer filterTimer;
        #endregion

        #region Data.Rules
        #endregion

        #region Data.VMs
        private DispatcherNotifiedObservableCollection<KonsumenThumbnailViewModel> konsumens;
        private ICollectionView konsumensCV;
        #endregion

        #region Data.Services
        private IViewAwareStatus viewAwareStatusService;
        private IMessageBoxService messageBoxService;
        private IUIVisualizerService uiVisualizerService;
        private IReferenceProvider referenceProvider;
        #endregion
        #endregion
        //private KonsumenViewModel selectedKonsumen;
        //private KonsumenFilterViewModel konsumenFilter;

        //private IMessageBoxService messageBoxService;
        //private IUIVisualizerService uiVisualizerService;
        //private IReferenceProvider referenceProvider;
        //#endregion

        #region Constructor
        [ImportingConstructor]
        public KonsumenSelectViewModel(
            IMessageBoxService messageBoxService,
            IUIVisualizerService uiVisualizerService,
            IReferenceProvider referenceProvider)
        {
            #region Constructor.SetupServices
            this.messageBoxService = messageBoxService;
            this.uiVisualizerService = uiVisualizerService;
            //this.viewAwareStatusService = viewAwareStatusService;
            this.referenceProvider = referenceProvider;
            //this.viewAwareStatusService.ViewLoaded += ViewAwareStatusService_ViewLoaded;
            #endregion

            #region Constructor.SetupCommands
            //KonsumenNewCommand = new SimpleCommand<Object, Object>(CanExecuteKonsumenNewCommand, ExecuteKonsumenNewCommand);
            //KonsumenRefreshCommand = new SimpleCommand<Object, Object>(CanExecuteKonsumenRefreshCommand, ExecuteKonsumenRefreshCommand);
            KonsumenFilterKeyUpCommand = new SimpleCommand<Object, Object>(CanExecuteKonsumenFilterKeyUpCommand, ExecuteKonsumenFilterKeyUpCommand);
            KonsumenMouseLeftButtonUpCommand = new SimpleCommand<Object, Object>(CanExecuteKonsumenMouseLeftButtonUpCommand, ExecuteKonsumenMouseLeftButtonUpCommand);
            #endregion

            #region Constructor.SetupDataWrappers
            #endregion

            #region Constructor.SetupValidationRules
            #endregion

            #region Constructor.SetupVMs
            Konsumens = new DispatcherNotifiedObservableCollection<KonsumenThumbnailViewModel>();
            KonsumensCV = CollectionViewSource.GetDefaultView(konsumens);
            #endregion

            Mediator.Instance.Register(this);

            #region Constructor.Filter
            filterTimer = new DispatcherTimer();
            filterTimer.Interval = TimeSpan.FromMilliseconds(
                Int32.Parse(ConfigurationManager.AppSettings["FilterResponsiveness"].ToString()));
            filterTimer.Tick += new EventHandler(LazyFilterCallback);
            #endregion

            LoadKonsumens();
        }
        #endregion

        #region Public Properties
        #region Public.Commands
        public SimpleCommand<Object, Object> KonsumenFilterKeyUpCommand { get; private set; }
        public SimpleCommand<Object, Object> KonsumenMouseLeftButtonUpCommand { get; private set; }
        #endregion

        #region Public.ViewMode
        #endregion

        #region Public.Data
        /// <summary>
        /// </summary>
        static PropertyChangedEventArgs filterKeywordChangeArgs =
            ObservableHelper.CreateArgs<KonsumenSelectViewModel>(x => x.FilterKeyword);
        public String FilterKeyword
        {
            get { return filterKeyword; }
            set
            {
                filterKeyword = value;
                NotifyPropertyChanged(filterKeywordChangeArgs);
                LazyFilter();
            }
        }
        #endregion

        #region Public.CachedCollection
        #endregion

        #region Public.DataVMs
        /// <summary>
        /// Loaded Konsumen
        /// </summary>
        static PropertyChangedEventArgs konsumensChangeArgs =
            ObservableHelper.CreateArgs<KonsumenSelectViewModel>(x => x.Konsumens);

        public DispatcherNotifiedObservableCollection<KonsumenThumbnailViewModel> Konsumens
        {
            get { return konsumens; }
            set
            {
                konsumens = value;
                NotifyPropertyChanged(konsumensChangeArgs);
            }
        }
        /// <summary>
        /// Loaded Konsumen
        /// </summary>
        static PropertyChangedEventArgs konsumensCVChangeArgs =
            ObservableHelper.CreateArgs<KonsumenSelectViewModel>(x => x.KonsumensCV);

        public ICollectionView KonsumensCV
        {
            get { return konsumensCV; }
            set
            {
                konsumensCV = value;
                NotifyPropertyChanged(konsumensCVChangeArgs);
            }
        }
        #endregion
        #endregion

        #region Command Handlers
        /// <summary>
        /// </summary>
        private bool CanExecuteKonsumenFilterKeyUpCommand(Object args)
        {
            return true;
        }
        /// <summary>
        /// </summary>
        private void ExecuteKonsumenFilterKeyUpCommand(Object args)
        {
            LazyFilter();
        }

        /// <summary>
        /// </summary>
        private bool CanExecuteKonsumenMouseLeftButtonUpCommand(Object args)
        {
            return true;
        }
        /// <summary>
        /// </summary>
        private void ExecuteKonsumenMouseLeftButtonUpCommand(Object args)
        {
            if (konsumensCV.CurrentPosition > -1)
            {
                CloseActivePopUpCommand.Execute(true);
            }
        }
        #endregion

        #region IViewStatusAwareInjectionAware Members
        #endregion
        
        #region Private Methods
        #region PrivateMethods.ViewLoaded
        private void ViewAwareStatusService_ViewLoaded()
        {
            LoadKonsumens();
        }
        #endregion

        #region PrivateMethods.Filter
        private void LazyFilter()
        {
            filterTimer.Stop();
            filterTimer.Start();
            Console.WriteLine("typing");
        }
        private void LazyFilterCallback(object sender, EventArgs e)
        {
            Console.WriteLine("stopped typing, filtering with keyword: " + filterKeyword);
            filterTimer.Stop();
            if (filterKeyword != "")
            {
                konsumensCV.Filter = new Predicate<object>(LazyFilterPredicate);
            }
            else
            {
                konsumensCV.Filter = null;
            }
        }
        private bool LazyFilterPredicate(object row)
        {
            KonsumenThumbnailViewModel ktvm = row as KonsumenThumbnailViewModel;
            return (ktvm.Nama.Contains(filterKeyword));
        }
        #endregion

        #region PrivateMethods.Loader
        /// <summary>
        /// loader
        /// </summary>
        private void LoadKonsumens()
        {
            referenceProvider.LazyFetchKonsumens(pageLoaded, PostLoadKonsumens);
        }

        /// <summary>
        /// post loader
        /// </summary>
        private void PostLoadKonsumens(List<Konsumen> dbKonsumens)
        {
            //rekursif sampai semua diload
            int pageSize = Int32.Parse(ConfigurationManager.AppSettings["LazyLoadPageSize"].ToString());
            KonsumenThumbnailViewModel ktvm = null;
            foreach (var item in dbKonsumens)
            {
                ktvm = new KonsumenThumbnailViewModel();
                ktvm.IdKonsumen = item.IdKonsumen;
                ktvm.Nama = item.Nama;
                ktvm.Alamat = item.Alamat;
                ktvm.Telepon = item.NoTelepon;
                ktvm.JenisKelamin = item.JenisKelamin;
                if (item.TanggalLahir.HasValue)
                    ktvm.TanggalLahir = item.TanggalLahir.Value;
                konsumens.Add(ktvm);
                Console.WriteLine("Nama: " + item.Nama);
            }

            if (dbKonsumens.Count != pageSize)
            {
                //basis
                //sudah habis, done loading
                isAllLoaded = true;
            }
            else
            {
                //rekurens
                ++pageLoaded;
                LoadKonsumens();
            }
        }
        #endregion
        #endregion
    }

}
